package com.xiaobias.a18;

import org.aopalliance.intercept.MethodInvocation;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.aop.Advisor;
import org.springframework.aop.aspectj.*;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.aop.framework.ReflectiveMethodInvocation;
import org.springframework.aop.interceptor.ExposeInvocationInterceptor;
import org.springframework.aop.support.DefaultPointcutAdvisor;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

public class A18 {

    static class Aspect {

        @Before("execution(* foo())")
        public void before1() {
            System.out.println("before1");
        }

        @Before("execution(* foo())")
        public void before2() {
            System.out.println("before2");
        }

        //@After("execution(* foo())")
        public void after() {
            System.out.println("after");
        }

        @AfterReturning("execution(* foo())")
        public void afterReturning() {
            System.out.println("afterReturning");
        }

        @AfterThrowing("execution(* foo())")
        public void afterThrowing() {
            System.out.println("afterThrowing");
        }

        @Around("execution(* foo())")
        public Object around(ProceedingJoinPoint pjp) throws Throwable {
            return null;
        }
    }

    static class Target {
        public void foo() {
            System.out.println("target foo");
        }
    }

    // all
    public static void main(String[] args) throws Throwable {

        AspectInstanceFactory factory = new SingletonAspectInstanceFactory(new Aspect());
        List<Advisor> list = new ArrayList<>();
        // 高级切面转化为低级切面
        for (Method method : Aspect.class.getDeclaredMethods()) {
            if (method.isAnnotationPresent(Before.class)) {
                // 解析切点
                String expression = method.getAnnotation(Before.class).value();
                AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut();
                pointcut.setExpression(expression);
                // 通知类
                AspectJMethodBeforeAdvice advice = new AspectJMethodBeforeAdvice(method, pointcut, factory);
                // 切面
                Advisor advisor = new DefaultPointcutAdvisor(pointcut, advice);
                list.add(advisor);
            } else if (method.isAnnotationPresent(AfterReturning.class)) {
                // 解析切点
                String expression = method.getAnnotation(AfterReturning.class).value();
                AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut();
                pointcut.setExpression(expression);
                // 通知类
                AspectJAfterReturningAdvice advice = new AspectJAfterReturningAdvice(method, pointcut, factory);
                // 切面
                Advisor advisor = new DefaultPointcutAdvisor(pointcut, advice);
                list.add(advisor);
            } else if (method.isAnnotationPresent(After.class)) {
                // 解析切点
                String expression = method.getAnnotation(After.class).value();
                AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut();
                pointcut.setExpression(expression);
                // 通知类
                AspectJAfterAdvice advice = new AspectJAfterAdvice(method, pointcut, factory);
                // 切面
                Advisor advisor = new DefaultPointcutAdvisor(pointcut, advice);
                list.add(advisor);
            } else if (method.isAnnotationPresent(AfterThrowing.class)) {
                // 解析切点
                String expression = method.getAnnotation(AfterThrowing.class).value();
                AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut();
                pointcut.setExpression(expression);
                // 通知类
                AspectJAfterThrowingAdvice advice = new AspectJAfterThrowingAdvice(method, pointcut, factory);
                // 切面
                Advisor advisor = new DefaultPointcutAdvisor(pointcut, advice);
                list.add(advisor);
            } else if (method.isAnnotationPresent(Around.class)) {
                // 解析切点
                String expression = method.getAnnotation(Around.class).value();
                AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut();
                pointcut.setExpression(expression);
                // 通知类
                AspectJAroundAdvice advice = new AspectJAroundAdvice(method, pointcut, factory);
                // 切面
                Advisor advisor = new DefaultPointcutAdvisor(pointcut, advice);
                list.add(advisor);
            }
        }
        for (Advisor advisor : list) {
            System.out.println(advisor);
        }
        /*
        @Before 前置通知会被转换为下面原始的 AspectJMethodBeforeAdvice 形式，该对象包含了如下信息
            a. 通知代码从哪儿来
            b. 切点是什么（这里为什么要切点，后面解释）
            c. 通知对象如果创建，本例共有一个 Aspect 对象
        类似的通知还有
            1. AspectJAroundAdvice(环绕通知)
            2. AspectJAfterReturningAdvice
            3. AspectJAfterThrowingAdvice
            4. AspectJAfterAdvice(环绕通知名)
         */

        // 2. 通知统一转换为环绕通知 MethodInterceptor
        /*
        其实无论 ProxyFactory 基于那种方式创建代理，最后干活（调用 advice）的是一个 MethodInvice 对象
            a. 因为 advisor 有多个，且一个套一个调用，因此需要一个调用链对象，即 MethodInvocation
            b. MethodInvocation 要知道 advice 有哪些，还要知道目标，调用次序如下：


            将 MethodInvocation 放入当前线程
                / -> before1 -----------------------------------------------        从当前线程获取  MethodInvocation
                /                                                           /
                /   / -> before2 ---------------------------                /       从当前线程获取  MethodInvocation
                /   /                                      /                /
                /   /   / -> target ----------- 目标    advice2           advice1
                /   /                                      /                /
                /                                                           /
                / -> after1 ------------------------------------------------
            c. 从图上看出，环绕通知才适合作为 advice2，因此其它 before、afterReturning 都会被转换成环绕通知
            d. 统一转换为环绕通知，体现的是设计模式中的适配器模式
                - 对外是为了方便使用要区分 before、afterReturning
                - 对内统一都是环绕通知，统一用 MethodInterceptor 表示

         此步骤获取所有执行时需要的 advice (静态)
            a. 即统一转换为 MethodInterceptor 环绕通知，这体现在方法名中的 Interceptors 上
            b. 适配如下
                - MethodBeforeAdviceAdapter 将 @Before AspectJMethodBeforeAdvice 适配为 MethodBeforeAdviceInterceptor
                - AfterReturningAdviceAdapter 将 @AfterReturning AspectJAfterReturningAdvice 适配为 AfterReturningAdviceInterceptor
         */
        Target target = new Target();
        ProxyFactory proxyFactory = new ProxyFactory();
        proxyFactory.setTarget(target);
        // 将 MethodInvocation 放入当前线程
        proxyFactory.addAdvice(ExposeInvocationInterceptor.INSTANCE);
        proxyFactory.addAdvisors(list);

        System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>");
        List<Object> methodInterceptorList = proxyFactory.getInterceptorsAndDynamicInterceptionAdvice(Target.class.getMethod("foo"), Target.class);
        for (Object o : methodInterceptorList) {
            System.out.println(o);
        }

        // 3. 创建并执行调用链(环绕通知s + 目标)
        MethodInvocation methodInvocation = new ReflectiveMethodInvocation(
                null, target, Target.class.getMethod("foo"), new Object[0], Target.class, methodInterceptorList
        ){};
        methodInvocation.proceed();

        /*
            此步骤模拟调用链过程，是一个简单的递归过程
                1. proceed() 方法调用链中下一个环绕通知
                2. 每个环绕通知内部继续调用 proceed()
                3. 调用到没有共多通知了，就调用目标方法
         */
    }
}
